package com.metadata_system.common.service;

import com.metadata_system.common.utils.RedisUtil;
import com.metadata_system.common.db.entity.AuthReflushToken;
import com.metadata_system.common.db.entity.AuthToken;
import com.metadata_system.common.db.mapper.AuthReflushTokenMapper;
import com.metadata_system.common.db.mapper.AuthTokenMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Slf4j
/**
 * token存储服务: redis,mysql
 * @author safi
 * @date 2019年10月11日11:25:12
 */
public class AuthTokenRepo {
    // redis 存储前缀
    @Value("${metadata-system.redis-token-pre:AUTH_TOKEN_}")
    private String redisPrefix = "AUTH_TOKEN_";

    @Autowired
    RedisUtil redisUtil;

    @Autowired(required = false)
    AuthTokenMapper authTokenMapper;

    @Autowired(required = false)
    AuthReflushTokenMapper authReflushTokenMapper;


    public AuthToken getByTokenId(Integer userId, String platform,String tokenId) {
//        log.info("userId: "+userId);
//        log.info("platform: "+platform);
//        log.info("tokenId: "+tokenId);
        String reidisKey = this.redisPrefix + platform + "_" + userId;
        AuthToken authToken = this.redisUtil.getValue(reidisKey, AuthToken.class);
        // 如果redis不存在
        if (authToken == null) {
            log.info("token 在 redis 中不存在,数据库中查找: {}", reidisKey);
            Example example = new Example(AuthToken.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userId);
            criteria.andEqualTo("platform", platform);
            criteria.andEqualTo("status", 1);
            AuthToken dbAuthToken = this.authTokenMapper.selectOneByExample(example);
            if (dbAuthToken == null) {
                return null;
            } else {
                // 如果数据库有,就将redis同步一下
                this.redisUtil.setValue(reidisKey, dbAuthToken);
            }
            return dbAuthToken;
        } else {
            if (!authToken.getTokenId().equals(tokenId)){
                return null;
            }
        }
        return authToken;
    }

    // 存储token

    public void insert(AuthToken authToken) {
        String reidisKey = this.redisPrefix + authToken.getPlatform() + "_" + authToken.getUserId();
        this.redisUtil.setValue(reidisKey, authToken);
        this.authTokenMapper.insert(authToken);
    }

    // 清空token

    public void clear(String platform, Integer userId) {
        Example example = new Example(AuthToken.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        criteria.andEqualTo("platform", platform);
        List<AuthToken> authTokenList = null;
        try {
            authTokenList = this.authTokenMapper.selectByExampleAndRowBounds(example, new RowBounds(0, 10));
        } catch (Exception e) {
            // 没有获取到token数据
        }
        // 数据库 清空 reflushToken
        if (!CollectionUtils.isEmpty(authTokenList)) {
            for (AuthToken token : authTokenList) {
                // 清空 token
                this.authTokenMapper.deleteByPrimaryKey(token.getId());

                // 清空 reflushToken
                Example reflushExample = new Example(AuthReflushToken.class);
                Example.Criteria reflushExampleCriteria = reflushExample.createCriteria();
                reflushExampleCriteria.andEqualTo("reflushTokenId", token.getReflushTokenId());
                this.authReflushTokenMapper.deleteByExample(reflushExample);

                // 清空当前token
                log.info("清空redis: " + (this.redisPrefix + token.getPlatform() + "_" + token.getUserId()));
                this.redisUtil.del(this.redisPrefix + token.getPlatform() + "_" + token.getTokenId());
            }
        }

//        // 数据库 清空 token
//        this.authTokenMapper.deleteByExample(example);
//        // redis 清空 token
//        this.redisUtil.del(reidisKey);
    }


}
